package cg.project.controller;


import cg.project.pojo.Result;
import cg.project.pojo.User;
import cg.project.service.UserService;
import cg.project.util.EmailUtil;
import cg.project.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
public class UserController {
    //控制层调用service层
    @Autowired
    private UserService userService;
    @Autowired
    private EmailUtil emailUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("sendCode")
    public Result sendCode(String email){
        User user = userService.login(email);

        if(user == null)
            return new Result("404","邮箱不存在");

        int power = user.getPower();
        int n = (int) (Math.random()*90000+10000);
        String serverCode = String.valueOf(n);
        emailUtil.send(email,serverCode);
        //session.setAttribute("code",serverCode);

        redisTemplate.opsForValue().set(email,serverCode,1, TimeUnit.MINUTES);
        return new Result("200","发送邮箱成功",user,power);
    }

    @PostMapping("login")
    public Result login(String email, String code) {
        User user = userService.login(email);
        if (user == null)
            return new Result("404", "邮箱不存在！");

        String token = JWTUtils.geneJsonWebToken(user);
        int power = user.getPower();

        return new Result("200", "登录成功！", token,power);
    }

    @GetMapping("loadUsers")
    public List<User> loadUsers(){
        return userService.getAllUsers();
    }

    @GetMapping("SearchUsers")
    public User SearchUsers(String searchQuery){

        return userService.SearchUsers(searchQuery);
    }

    @GetMapping("SearchUsersById")
    public User SearchUsersByid(int id){

        return userService.SearchUsersByid(id);
    }


    @GetMapping("deleteuser")
    public void DeleteUser(int userId){
        userService.DeleteUser(userId);
    }

    @PostMapping("updateUser")
    public void UpdateUser(int userid,String username,String email,String pwd){
        userService.Updateuser(userid,username,email,pwd);
    }
}